package dnl.jexem.camouflaj;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dnl.jexem.cmd.Command;

public class Client {

	private static final Logger logger = LoggerFactory.getLogger(Client.class.getSimpleName());

	public static void main(String[] args) {
		if (args.length < 3) {
			printUsageAndExit();
		}
		String propsFileName = args[0];

		File propsFile = new File(propsFileName);
		if (!propsFile.exists()) {
			System.err.println("Could not find " + propsFileName);
			System.exit(1);
		}

		RemoteCommandManager remoteCommandManager = null;
		try {
			Config config = new Config(propsFile);
			remoteCommandManager = config.getRemoteCommandManager();
		} catch (IOException e) {
			e.printStackTrace();
			handleException(e);
		}

		Command command = new Command(Arrays.copyOfRange(args, 1, args.length));
		String commandId = remoteCommandManager.placeCommand(command);
		logger.info("Waiting for ack on command with id={}", commandId);
		remoteCommandManager.waitForAcknowledge(commandId, 30);
		logger.info("command was sent.");
		remoteCommandManager.waitForExecution(commandId);
		ExecutionSummary executionSummary = remoteCommandManager.readExecutionSummary(commandId);
		System.out.println("Exit Status: " + executionSummary.getExitStatus());
		System.out.println("Errors: ");
		System.out.println(executionSummary.getErrorOutput() == null? "" : executionSummary.getErrorOutput());
		System.out.println(executionSummary.getExceptions() == null? "" : executionSummary.getExceptions());
		System.out.println("Output: ");
		System.out.println(executionSummary.getOutput());
	}

	private static void printUsageAndExit() {
		System.err.println("Usage: Client propertiesFilePath command");
		System.exit(1);
	}

	private static void handleException(Exception e) {
		System.err.println("Error: " + e.getMessage());
		System.exit(1);
	}
}
